#include "vcl_stl.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <netdb.h>

#include "h_base.h"
#include "h_xml.h"
using namespace h_base;

#include "simbat.h"
using namespace simbat;

#include "bkbase.h"

#define PASS_KEY "sim bat 1.0.0   "

static HString SyslogDir;
static HSyslog Syslog;
static HString ShrDir;

static void LoadFromCfg(HXmlTree &Cfg)
{
   SyslogDir = EnvEvaluate(Cfg.GetValue("SYSLOG_DIR", "$SIMBAT_BASE/etc"));
   Syslog.Setup(SyslogDir, Cfg.GetValueUpper("SYSLOG_LEVEL", "INFO"));
   ShrDir = EnvEvaluate(Cfg.GetValue("SHR_DIR", "$SIMBAT_BASE/shr"));
}

int main(int argc, char *argv[])
{
   if ( strchr(argv[0], '/') != NULL )
   {
      SetBaseByPath(argv[0]);
   }

   char TmpStr[501];
   HXmlTree Cfg;
   HString FileName = EnvEvaluate("$SIMBAT_BASE/etc/config.xml");

   if ( argc != 2 )
   {
      fprintf(stderr, "Usage : [PATH]/simbat_pass oper_id\n");
      return 8;
   }

   if ( !Cfg.LoadFromFile(FileName.c_str()) )
   {
      fprintf(stderr, "Load config.xml fail, %s",
         Cfg.GetErrorString().c_str());
      return 8;
   }

   LoadFromCfg(Cfg);

   char NewPass[200 + 1];
   char NewPass2[200 + 1];

   system("stty -echo");
   fprintf(stderr, "Please enter password: ");
   ReadLine(stdin, NewPass, 200);
   fprintf(stderr, "\nPlease enter password again: ");
   ReadLine(stdin, NewPass2, 200);
   system("stty echo");
   fprintf(stderr, "\n");

   if ( strcmp(NewPass, NewPass2) != 0 )
   {
      fprintf(stderr, "password not match\n");
      return 8;
   }

   NewPass[32] = '\0';
   BkRightTrim(NewPass);

   int Len = strlen(NewPass);

   if ( Len < 32 )
   {
      memset(NewPass + Len, '\0', 32 - Len);
   }

   FileName = ShrDir + "/etc/auth.xml";

   {
      HFileLockWrite Lock("$SIMBAT_BASE/tmp/config.lck");
      if ( !Cfg.LoadFromFile(FileName.c_str()) )
      {
         fprintf(stderr, "Load auth.xml fail, %s",
            Cfg.GetErrorString().c_str());
         return 8;
      }
      vector<HXmlTree*> Nodes;
      Cfg.GetChildren("LOGIN", Nodes);
      BkTeaEncrypt(NewPass, PASS_KEY, 32);
      BkHexToAsc(NewPass, TmpStr, 32);
      TmpStr[32 * 2] = '\0';
      bool Found = false;
      for ( int i = 0; i < Nodes.size() && !Found; i++ )
      {
         HXmlTree *Login = Nodes[i];
         if ( Login->GetValue("ID") == argv[1] )
         {
            Login->SetValue("PASSWORD", TmpStr);
            Found = true;
         }
      }
      if ( !Found )
      {
         HXmlTree *Login = new HXmlTree(&Cfg, "LOGIN");
         Login->SetValue("ID", argv[1]);
         Login->SetValue("PASSWORD", TmpStr);
      }
      Cfg.SaveToFile(FileName.c_str());
   }

   system("simbat_ctl reload_config 2> /dev/null");
   fprintf(stderr, "\nPassword for %s has been changed.\n\n", argv[1]);
   return 0;
}
